package com.example.demo.pay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.example.demo.entity.BookInfo;
import com.example.demo.entity.Orders;
import com.example.demo.pojo.BSResult;
import com.example.demo.utils.BSResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class Alipay extends AbstractPay{
    @Autowired
    private AlipayConfig alipayConfig;

    @Override
    public void prepareAndPay(PayContext payContext) throws IOException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getOpenApiDomain(),
                alipayConfig.getAppId(),
                alipayConfig.getMerchantPrivateKey(),
                alipayConfig.getFormat(),
                alipayConfig.getCharset(),
                alipayConfig.getAlipayPublicKey(),
                alipayConfig.getSignType()); //获得初始化的AlipayClient

        Orders order = payContext.getOrder();
        BookInfo book = payContext.getBookInfos().get(0);
        HttpServletResponse httpResponse = payContext.getResponse();



        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
        alipayRequest.setReturnUrl(alipayConfig.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());//在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\""+order.getOrderId()+"\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":\""+order.getPayment()+"\"," +
                "    \"subject\":\""+book.getOutline()+"\"," +
                "    \"body\":\""+book.getOutline()+"\"," +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                "    \"extend_params\":{" +
                "    \"sys_service_provider_id\":\"2088511833207846\"" +
                "    }"+
                "  }");//填充业务参数
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + alipayConfig.getCharset());
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @Override
    public void afterPay(PayContext payContext) {
    }

    public AlipayTradeQueryResponse tradeQuery(PayContext payContext, HttpServletRequest request) throws AlipayApiException, IOException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getOpenApiDomain(),
                alipayConfig.getAppId(),
                alipayConfig.getMerchantPrivateKey(),
                alipayConfig.getFormat(),
                alipayConfig.getCharset(),
                alipayConfig.getAlipayPublicKey(),
                alipayConfig.getSignType()); //获得初始化的AlipayClient

        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        Orders orders=payContext.getOrder();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ orders.getOrderId()+"\"}");

        AlipayTradeQueryResponse queryResponse=alipayClient.execute(alipayRequest);

        return queryResponse;


        /*
        //请求
        String result = alipayClient.execute(alipayRequest).getBody();

        HttpServletResponse httpResponse=payContext.getResponse();
        httpResponse.setContentType("text/html;charset=" + alipayConfig.getCharset());
        httpResponse.getWriter().write(result);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        */
    }

    public BSResult tradeRefund(PayContext payContext) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getOpenApiDomain(),
                alipayConfig.getAppId(),
                alipayConfig.getMerchantPrivateKey(),
                alipayConfig.getFormat(),
                alipayConfig.getCharset(),
                alipayConfig.getAlipayPublicKey(),
                alipayConfig.getSignType()); //获得初始化的AlipayClient

        AlipayTradeRefundRequest refundRequest=new AlipayTradeRefundRequest();
        Orders orders=payContext.getOrder();
        refundRequest.setBizContent("{" +
                "    \"out_trade_no\":\""   +orders.getOrderId()+   "\"," +
                "    \"refund_amount\":\""   +orders.getPayment()+   "\"," +
                "    \"refund_currency\":\""  +"CNY"+   "\"," +
                "    \"refund_reason\":\"正常退款\""+
                "  }");//填充业务参数

        AlipayTradeRefundResponse refundResponse=alipayClient.execute(refundRequest);
        String msg=refundResponse.getMsg();
        if(!"Business Failed".equals(msg)){
            return BSResultUtils.success(refundResponse);
        }
        else
            return BSResultUtils.build(404,"FAILED");

    }

    public BSResult defundQuery(PayContext payContext) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getOpenApiDomain(),
                alipayConfig.getAppId(),
                alipayConfig.getMerchantPrivateKey(),
                alipayConfig.getFormat(),
                alipayConfig.getCharset(),
                alipayConfig.getAlipayPublicKey(),
                alipayConfig.getSignType()); //获得初始化的AlipayClient


        AlipayTradeFastpayRefundQueryRequest alipayRequest=new AlipayTradeFastpayRefundQueryRequest();

        Orders order=payContext.getOrder();
        String orderId=order.getOrderId();
        alipayRequest.setBizContent(" { " +
                "\"out_trade_no\":"+orderId+","+
                "\"out_request_no\":"+orderId+"}");

        AlipayTradeFastpayRefundQueryResponse response=alipayClient.execute(alipayRequest);

        String msg=response.getMsg();

        if(!"Business Failed".equals(msg)){
            return BSResultUtils.success(response);

        }else{

            return BSResultUtils.build(404,"FAILED");
        }

    }






}
